using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using Tools;

namespace UserRegistration
{
    public class ContactRegistationServer
    {
        private DataStructures.HWInfo hardwareInfo;
        private TheApplication caller;

        public ContactRegistationServer(DataStructures.HWInfo hardwareInfo, TheApplication caller)
        {
            this.hardwareInfo = hardwareInfo;
            this.caller = caller;
        }

        public void GetRegistrationKey()
        {
            WebResponse registrationKey = null;
            String url_string = "http://www.milen.pl/register.php"
                                + "?CPU=" + System.Web.HttpUtility.UrlEncode(hardwareInfo.cpuID)
                                + "&BIOS=" + System.Web.HttpUtility.UrlEncode(hardwareInfo.biosID)
                                + "&MB=" + System.Web.HttpUtility.UrlEncode(hardwareInfo.baseID)
                                + "&DISK=" + System.Web.HttpUtility.UrlEncode(hardwareInfo.diskID)
                                + "&MAC=" + System.Web.HttpUtility.UrlEncode(hardwareInfo.macID)
                                + "&VIDEO=" + System.Web.HttpUtility.UrlEncode(hardwareInfo.videoID);
            try
            {
                WebRequest requestRegistration = WebRequest.Create(url_string);
                registrationKey = requestRegistration.GetResponse();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Failed to contact server");
                caller.Invoke(caller.ServerNotification,new Object[]{null});
                return;
            }

            Stream stream = registrationKey.GetResponseStream();

            StreamReader reader = new StreamReader(stream);

            String s = reader.ReadToEnd();
            reader.Close();

            
            int i = s.IndexOf("key:");
            if( i >= 0)
            {
                String key = s.Substring(i+4, 19);
                caller.Invoke(caller.ServerNotification,new Object[]{key});
            }
            else
                caller.Invoke(caller.ServerNotification,new Object[]{null});
        }
    }
}
